import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';

const Right2 = () => {
    const chartRef = useRef(null); // 用于引用 ECharts 实例的 ref
    const [chart, setChart] = useState(null); // ECharts 实例的状态
    const [data, setData] = useState([]); // 图表数据
    const dataLength = 200; // 控制数据长度

    useEffect(() => {
        // 初始化数据和图表
        const initialHumidity = Math.floor(Math.random() * 6) + 45; // 初始湿度调整为45%
        const now = new Date().getTime();
        setData([{ time: now, humidity: initialHumidity }]);

        // 初始化图表
        const initChart = () => {
            const echartsInstance = echarts.init(chartRef.current);
            setChart(echartsInstance);

            const option = {
                title: {
                    text: '湿度变化',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: '{b0}<br />{a0}: {c0}%',
                },
                xAxis: {
                    type: 'time',
                    boundaryGap: false,
                    axisLabel: {
                        formatter: (value) => echarts.format.formatTime('MM:ss', value),
                    },
                },
                yAxis: {
                    type: 'value',
                    min: 20,
                    max: 80,
                    axisLabel: {
                        formatter: '{value} %',
                    },
                },
                series: [
                    {
                        name: '湿度',
                        type: 'line',
                        smooth: true,
                        data: data.map(item => [item.time, item.humidity]),
                        lineStyle: {
                            color: '#007acc',
                            width: 2,
                        },
                    },
                ],
            };

            echartsInstance.setOption(option);
        };

        initChart(); // 初始化图表

        // 开始随机更新数据
        const intervalId = setInterval(() => {
            const now = new Date().getTime();
            const humidityChange = Math.random() > 0.5 ? -1 : 1; // 随机增加或减少湿度
            let newHumidity = data[data.length - 1].humidity + humidityChange / 10; // 减小变化幅度
            newHumidity = Math.max(20, Math.min(80, newHumidity)); // 限制湿度在20%-80%之间

            if (data.length >= dataLength) {
                setData(prevData => prevData.slice(1)); // 移除旧数据
            }

            setData(prevData => [...prevData, { time: now, humidity: newHumidity }]); // 更新数据

            // 更新图表数据
            if (chart) {
                chart.setOption({
                    series: [{
                        data: data.map(item => [item.time, item.humidity]),
                    }],
                });
            }
        }, 5000);

        return () => clearInterval(intervalId); // 组件卸载时清除定时器
    }, [chart, data]);

    return (
        <div>
            <div id="chart" style={{ width: '100%', height: '170px' }} ref={chartRef}></div>
        </div>
    );
};

export default Right2;
